package mudfox.controller;

import mudfox.entity.GenericEntity;
import mudfox.entity.Result;
import mudfox.repository.GenericEntityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

// @Api(tags = "GenericEntity Controller")
@RestController
@RequestMapping("/GenericEntity")
public class GenericEntityController extends BaseController {
    @Autowired
    private GenericEntityRepository repository;

    public GenericEntityController() {
        functions.add("topic:topic");
        functions.add("label:label");
        functions.add("get_topics");
    }

    @GetMapping("")
    Result index() {
        return show_status();
    }

    @GetMapping("/show_api")
    Result showApi() {
        return show_api();
    }

    @GetMapping("/get_topics")
    Result getTopics() {
        Iterable<String> topics = repository.getTopics();
        return new Result(entry, "topics", topics);
    }

    @GetMapping("/id/{id}")
    Result findById(@PathVariable Integer id) {
        Optional<GenericEntity> item = repository.findById(id);
        return new Result(entry, "item", item);
    }

    @GetMapping("/topic/{topic}")
    Result findByTopic(@PathVariable String topic) {
        Iterable<GenericEntity> items = repository.findByTopic(topic);
        return new Result(entry, topic, items);
    }

    @GetMapping("/label/{label}")
    Result findByLabel(@PathVariable String label) {
        Iterable<GenericEntity> items = repository.findByLabelContaining(label);
        return new Result(entry, items);
    }

    @PostMapping("/item")
    Result addItem(@RequestBody GenericEntity entity) {
        GenericEntity result = repository.save(entity);
        return new Result(entry, result.getId());
    }

    @PutMapping("/id/{id}")
    Result setItem(@RequestBody GenericEntity newEntity,
                   @PathVariable Integer id) {
        newEntity.setId(id);
        GenericEntity result = repository.save(newEntity);
        return new Result(entry, "updated_id", result.getId());
    }

    @DeleteMapping("/id/{id}")
    Result removeItem(@PathVariable Integer id) {
        repository.deleteById(id);
        return new Result(entry, "deleted_id", id);
    }
}
